<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Http\Requests;
use Hash;
use DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    //显示后台用户添加页面
    public function getAdd()
    {
    	//解析模板
    	return view('Admin.user.add');
    }

    //接收提交数据 进行添加
    public function postInsert(UserRequest $request)
    {
    	//dd($request->all());
    	// if(!$request->input('username')){
    	// 	return back()->with('error','111');
    	// }
    	// $this->validate($request,[
     //        'username'=>'required',
     //        'password'=>'rwquired',
     //        'repassword'=>'required',
     //        'email'=>'required',
     //        'phone'=>'required'
     //    ]);
    	//处理数据添加到数据库
    	$data=$request->only(['username','password','email','phone']);
    	$data['token']=str_random(50);
    	//密码加密
    	$data['password']=Hash::make($data['password']);
    	//dd($data);
    	//执行数据的插入
    	$res=DB::table('users')->insert($data);
    	if($res){
    		return redirect('/admin/user/index')->with('success','用户添加成功');
    	}else{ 
    		return back()->with('error','用户添加失败');
    	}
    }

    //显示用户列表
    public function getIndex(Request $request)
    {
    	//获得显示的条数
    	$num=$request->input('num',10);
    	//判断是否有关键字
    	if($request->input('keywords')){
    		$users=DB::table('users')
    		->where('username','like','%'.$request->input('keywords').'%')
    		->paginate($num);
    	}else{
	    	//查询所有用户
	    	$users=DB::table('users')->paginate($num);   		
    	}
    	//获取所有参数
    	$data=$request->all();
    	//解析模板
    	return view('admin.user.index',['users'=>$users,'data'=>$data]);
    }

    //用户删除
    public function getDelete($id)
    {
    	$res=DB::table('users')->where('id',$id)->delete();

    	if($res){
    		return redirect('/admin/user/index')->with('success','用户删除成功');
    	}else{ 
    		return back()->with('error','用户删除失败');
    	}
    }

    //用户修改
    public function getEdit($id)
    {
    	$res=DB::table('users')->where('id',$id)->first();

    	//解析模板显示修改表单
    	return view('admin.user.edit',['userinfo'=>$res]);
    }

    //执行修改
    public function postUpdate(Request $request)
    {
    	//dd($request->all());
    	$id = $request->input('id');
    	//dd($id);
    	$data = $request->only(['username','email','phone','status']);
    	//执行修改
    	$res = DB::table('users')->where('id',$id)->update($data);
   		if($res){
            return redirect('/admin/user/index')->with('success','用户修改成功');
        }else{
            return back()->with('error','用户修改失败');
        }
    }

}
